import { SET_ROUTES, SET_MENU_LIST } from '../actionType'
import { getUserRouters } from '@/api/user'
import { dynamicImport } from '@/router/utils'

import Layout from '@/layout'


export const setRoutesAction = (data) => ({ type: SET_ROUTES, data })
export const setMenuListAction = (data) => ({ type: SET_MENU_LIST, data })

export const getRouters = () => async (dispatch) => {
  try {
    const { code, data } = await getUserRouters()
    if (code === 200) {
      console.log(data, '原始路由')
      // 生成路由
      const asyncRoutes = filterAsyncRoutes(data)
      //  生成侧边栏
      const menuList = genMenuList(data)

      await dispatch(setRoutesAction(asyncRoutes))

      await dispatch(setMenuListAction(menuList))

    }
  } catch (err) {
    console.log(err);
  }
}

/**
 * 筛选路由
 * @param {*} routes 
 * @returns 
 */

export function filterAsyncRoutes(routes) {
  const res = []
  routes.forEach(route => {
    const tmp = {}
    if (route.component) {
      tmp.meta = route.meta
      tmp.path = route.path.includes('/')
        ? route.path.replace(/\//g, '')
        : route.path

      if (route.name) {
        tmp.name = route.name
      }
      if (route.component === 'Layout') {
        tmp.element = <Layout />
      } else {
        let Component = dynamicImport(() => import(`@/pages/${route.component}`))
        tmp.element = <Component />
      }
      if (route.children) {
        tmp.children = filterAsyncRoutes(route.children)
      }
      res.push(tmp)
    }
  })
  return res
}

/**
 * 生成左侧菜单
 * @param {*} routes 
 * @returns 
 */
export function genMenuList(routes) {
  const res = []
  routes.forEach(route => {
    if (route.path === '/') {
      res.push(...route.children)
    } else {
      res.push(route)
    }
  })
  handlePath(res)
  console.log(res , 'genMenuList')
  return res

}

/**
 * 修改路径
 */
function handlePath(res, path = '') {
  res.forEach(item => {
    let pathArr = []
    item.path = item.path.includes('/') ? item.path.replace(/\//g, '') : item.path
    pathArr.push(path)
    pathArr.push(item.path)
    item.path = pathArr.join('/') 
    if (item.children) {
      handlePath(item.children, item.path)
    }
  })
}